<?php

namespace App\Http\Controllers;

use App\Events\SellMember;
use App\Events\SendNoticeToOne;
use App\Models\Deal;
use App\Models\DealBuyer;
use App\Models\DealLog;
use App\Models\EDealLog;
use App\Models\PowerLog;
use App\Models\Recharge;
use App\Models\RentCloth;
use App\Models\Shop;
use App\Models\ShopCrowd;
use App\Models\ShopRole;
use App\Models\User;
use App\Models\UserCard;
use App\Models\Wallet;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    /**
     * 微信支付
     *
     * @param Request $request
     * @return void
     * @Description
     * @author wjx
     */
    public function payByWechat(Request $request)
    {
        return app('wechat_pay')->app([
            'out_trade_no' => time(), // 商户订单流水号，与支付宝 out_trade_no 一样
            'total_fee' => '0.01' * 100, // 与支付宝不同，微信支付的金额单位是分。
            'body' => '微信支付测试', // 订单描述
        ]);
    }
    /**
     * 企业付款到个人账号
     *
     * @param Request $request
     * @return void
     * @Description
     * @author wjx
     */
    public function wechatTransfer(Request $request)
    {
        $order = [
            'partner_trade_no' => time(), //商户订单号
            'openid' => 'oH2sd6Ikpll90wFUH-OGERJyV8W4', //收款人的openid
            'check_name' => 'NO_CHECK', //NO_CHECK：不校验真实姓名\FORCE_CHECK：强校验真实姓名
            // 're_user_name'=>'张三',              //check_name为 FORCE_CHECK 校验实名的时候必须提交
            'amount' => '100', //企业付款金额，单位为分
            'type' => 'app',
            'desc' => '帐户提现测试',
        ];
        return app('wechat_pay')->transfer($order);
    }

    public function wechatNotify()
    {
        $data = app('wechat_pay')->verify();
        if ($data) {
            try {
                $order = Recharge::where('out_trade_no', $data->out_trade_no)->first();
                $wallet = Wallet::where('user_id', $order->user_id)->first();
                $user = User::where('id', $order->user_id)->with('member')->first();
                if ($order->status !== 2) {
                    $order->update([
                        'pay_at' => Carbon::now(),
                        'status' => 2,
                        'payment_no' => $data->transaction_id,
                    ]);

                    switch ($order->type) {
                        case '1': //充值余额
                            $this->recharge_to_wallet($order, $wallet);
                            break;
                        case '2': //充值会员
                            $this->recharge_to_member($order, $wallet, $user);
                            break;
                        case '3': //续费会员
                            $this->renew_member($user, $order);
                            break;
                        case '4': //项目认购
                            $this->add_crowd($order, $user, $data);
                            break;
                        case '5': //充值押金
                            $this->recharge_to_deposit($order, $wallet, $user);
                            break;
                        case '6': //购买E币
                            $this->buy_tmc($wallet, $user, $data);
                            break;
                        case '7': //换购商品
                            $this->buy_order($wallet, $user, $data);
                            break;
                        case '8': //购买礼品卡
                            $this->buy_present_card($wallet, $user, $order);
                            break;
                        case '9': //升级衣袋
                            $this->buy_bag($wallet, $user, $order);
                            break;
                        default:

                            break;
                    }
                }
            } catch (\Exception $e) {
                $e->getMessage();
                Log::info('wechat error', [
                    'error' => $e->getMessage(),
                ]);
            }
            return app('wechat_pay')->success();
        }
    }

    public function recharge_to_wallet($order, $wallet)
    {
        $wallet->money = $wallet->money + $order->money;
        $wallet->save();
        event(new SendNoticeToOne($wallet, 2, 7));
    }

    public function recharge_to_member($order, $wallet, $user)
    {
        $user->is_member = 1;
        switch ($user->member->time) {
            case '3': //月卡
                $user->member_start_time = time();
                $user->member_end_time = strtotime('+1month');
                break;
            case '6': //年卡
                $user->member_start_time = time();
                $user->member_end_time = strtotime('+1year');
                break;
            default:
                break;
        }
        $user->save();
        $wallet->deposit = $order->deposit;
        $wallet->save();
        $money = bcadd($order->money, 500, 2);
        DealLog::add_log($user->id, 0, $money, 2, '购买会员消耗(微信)');
        event(new SellMember($order->id));
    }

    public function renew_member($user, $order)
    {
        $user->is_member = 1;
        $user->level = $order->level;
        switch ($user->member->time) {
            case '3': //月卡
                $user->member_end_time = strtotime("+1month", $user->member_end_time);
                break;
            case '6': //年卡
                $user->member_end_time = strtotime('+1year', $user->member_end_time);
                break;
            default:
                break;
        }
        $user->save();
        DealLog::add_log($user->id, 0, $order->money, 2, '续费会员消耗(微信)');
        event(new SellMember($order->id));
    }

    public function add_crowd($order, $user, $data)
    {
        switch ($order->money) {
            case '500':
                $crowd_type = 0;
                break;
            case '1300':
                $crowd_type = 1;
                break;
            case '5000':
                $crowd_type = 2;
                break;
            default:
                break;
        }
        $crowd = new ShopCrowd();
        $crowd->user_id = $user->id;
        $crowd->shop_id = $order->shop_id;
        $crowd->phone = $user->phone ? $user->phone : '';
        $crowd->crowd_type = $crowd_type;
        $crowd->money = $order->money;
        $crowd->pay_type = 1;
        $crowd->is_trust = $order->is_trust;
        $crowd->out_no = $data->transaction_id;
        $crowd->save();

        $crowd_total = ShopCrowd::where('shop_id', $crowd->shop_id)->sum('money');
        $shop = Shop::where('id', $crowd->shop_id)->first();

        DB::beginTransaction();
        try {
            DealLog::add_log($user->id, 0, $order->money, 2, '认购项目消耗(微信)');
            if ((int) $crowd_total >= (int) $shop->shop_price) {
                $shop->crowd_funding_end = time();
                $shop->status = 3;
                $shop->save();
                event(new SendNoticeToOne($shop, 2, 3));

                $now = Carbon::now()->toDateTimeString();
                //分配会员卡
                $role_dz = ShopRole::where(['shop_id' => $crowd->shop_id, 'role' => 1])->orderBy('hot_spot', 'desc')->first();
                if ($role_dz) {
                    $role_dz->status = 1;
                    $role_dz->save();
                    foreach (range(1, 30) as $index) {
                        $data_dz[] = [
                            'user_id' => $role_dz->user_id,
                            'shop_id' => $role_dz->shop_id,
                            'card_type' => 1,
                            'card_level' => 1,
                            'code' => strtoupper(str_random(20)),
                            'is_used' => 0,
                            'created_at' => $now,
                            'updated_at' => $now,
                        ];
                    }
                    UserCard::insert($data_dz);
                    event(new SendNoticeToOne($role_dz, 2, 2));
                }

                $role_dy = ShopRole::where(['shop_id' => $crowd->shop_id, 'role' => 2])->orderBy('hot_spot', 'desc')->first();
                if ($role_dy) {
                    $role_dy->status = 1;
                    $role_dy->save();
                    foreach (range(1, 18) as $index) {
                        $data_dy[] = [
                            'user_id' => $role_dy->user_id,
                            'shop_id' => $role_dy->shop_id,
                            'card_type' => 1,
                            'card_level' => 1,
                            'code' => strtoupper(str_random(20)),
                            'is_used' => 0,
                            'created_at' => $now,
                            'updated_at' => $now,
                        ];
                    }
                    UserCard::insert($data_dy);
                    event(new SendNoticeToOne($role_dy, 2, 2));
                }

                $role_md = ShopRole::where(['shop_id' => $crowd->shop_id, 'role' => 3])->orderBy('hot_spot', 'desc')->first();
                if ($role_md) {
                    $role_md->status = 1;
                    $role_md->save();
                    foreach (range(1, 9) as $index) {
                        $data_md[] = [
                            'user_id' => $role_md->user_id,
                            'shop_id' => $role_md->shop_id,
                            'card_type' => 1,
                            'card_level' => 1,
                            'code' => strtoupper(str_random(20)),
                            'is_used' => 0,
                            'created_at' => $now,
                            'updated_at' => $now,
                        ];
                    }
                    UserCard::insert($data_md);
                    event(new SendNoticeToOne($role_md, 2, 2));
                }

                //添加会员
                ShopCrowd::where('shop_id', $crowd->shop_id)->get()->each(function ($item) {
                    if ($item->is_trust == 0) { //成功未托管
                        $user = user::where('id', $item->user_id)->first();
                        switch ($item->crowd_type) {
                            case '0':
                                if ($user->is_member == 1) {
                                    $user->member_end_time = strtotime("+2month", $user->member_end_time);
                                } else {
                                    $user->member_start_time = time();
                                    $user->level = 3;
                                    $user->member_end_time = strtotime("+2month");
                                }
                            case '1':
                                if ($user->is_member == 1) {
                                    $user->member_end_time = strtotime("+6month", $user->member_end_time);
                                } else {
                                    $user->member_start_time = time();
                                    $user->level = 3;
                                    $user->member_end_time = strtotime("+6month");
                                }
                            case '2':
                                if ($user->is_member == 1) {
                                    $user->member_end_time = strtotime("+2year", $user->member_end_time);
                                } else {
                                    $user->member_start_time = time();
                                    $user->level = 3;
                                    $user->member_end_time = strtotime("+2year");
                                }
                                break;
                            default:
                                break;
                        }
                        $user->is_member = 1;
                        $user->save();
                    }
                });

            }
            DB::commit();
        } catch (\Exception $exception) {
            Log::info('wechat error5', [
                'error' => $exception->getMessage(),
            ]);
            DB::rollBack();
        }

    }

    public function recharge_to_deposit($order, $wallet, $user)
    {
        $user_card = UserCard::where('id', $order->user_card_id)->first();

        switch ($user_card->card_level) {
            case '1':
                $user->member_end_time = strtotime('+1month');
                $user->level = 3;
                break;
            case '2':
                $user->member_end_time = strtotime('+3month');
                $user->level = 3;
                break;
            case '3':
                $user->member_end_time = strtotime('+1year');
                $user->level = 6;
                break;
            default:
                break;
        }
        $user_card->is_used = 1;
        $user_card->used_by = $user->id;
        $user_card->used_at = date('Y-m-d H:i:s');
        $user->member_start_time = time();
        $user->is_member = 1;
        $wallet->deposit = $order->money;
        DB::beginTransaction();
        try {
            $user_card->save();
            $user->save();
            $wallet->save();

            DealLog::add_log($user->id, 0, $order->money, 2, '押金消耗(微信)');
            DB::commit();
        } catch (\Exception $exception) {
            Log::info('wechat error7', [
                'error' => $exception->getMessage(),
            ]);
            DB::rollBack();
        }
    }

    public function buy_tmc($wallet, $user, $data)
    {
        $deal_buyer = DealBuyer::where('out_trade_no', $data->out_trade_no)->first();
        $deal = Deal::where('id', $deal_buyer->deal_id)->with('user')->first();
        $seller_wallet = Wallet::where('user_id', $deal->user_id)->first();
        $deal->rest_amount = bcsub($deal->rest_amount, $deal_buyer->total_amount, 4);
        $deal_buyer->status = 3;
        $deal_buyer->payment_no = $data->transaction_id;
        $deal_buyer->pay_at = Carbon::now();

        $seller_wallet->money = bcadd($seller_wallet->money, $deal_buyer->total_price, 2);

        $wallet->tmc = bcadd($wallet->tmc, $deal_buyer->total_amount, 4);

        DB::beginTransaction();
        try {
            $deal->save();
            if ($deal->rest_amount == 0) {
                $deal->status = 3;
                $deal->save();
            }
            $deal_buyer->save();
            $wallet->save();
            $seller_wallet->save();
            event(new SendNoticeToOne($deal_buyer, 2, 11));
            DealLog::add_log($user->id, $deal->user_id, $deal_buyer->total_price, 2, '购买E格码消耗(微信)');
            DealLog::add_log($deal->user_id, $user->id, $deal_buyer->total_price, 1, '卖出E格码增加');
            EDealLog::add_log($user->id, $deal->user_id, $deal_buyer->total_amount, 1, '买入E格码增加', 0);
            EDealLog::add_log($deal->user_id, $user->id, $deal_buyer->total_amount, 2, '卖出E格码减少', 0);
            DB::commit();
        } catch (\Exception $exception) {
            Log::info('wechat error6', [
                'error' => $exception->getMessage(),
            ]);
            DB::rollBack();
        }
    }

    public function buy_order($wallet, $user, $data)
    {
        $rent_cloth = RentCloth::where('out_trade_no', $data->out_trade_no)->first();
        $rent_cloth->status = 3;
        $rent_cloth->pay_at = Carbon::now();
        $new_power = bcsub($wallet->computing_power, 50, 2);

        DB::beginTransaction();
        try {
            $rent_cloth->save();

            Wallet::where('user_id', $user->id)->update([
                'computing_power' => $new_power,
            ]);
            PowerLog::add_log($user->id, 3, 50, 2);
            DealLog::add_log($user->id, 0, $rent_cloth->total_price, 2, '换购消耗(微信)');
            DB::commit();
        } catch (\Exception $exception) {
            Log::info('wechat error7', [
                'error' => $exception->getMessage(),
            ]);
            DB::rollBack();
        }
    }

    public function buy_present_card($wallet, $user, $order)
    {
        switch ($order->money) {
            case '499.00':
                $card_level = 1;
                break;
            case '1300.00':
                $card_level = 2;
                break;
            case '4990.00':
                $card_level = 3;
                break;
            default:
                break;
        }
        $card = new UserCard();
        $card->user_id = $user->id;
        $card->card_id = $order->present_card_id;
        $card->card_type = 2;
        $card->card_level = $card_level;
        $card->code = strtoupper(str_random(20));
        $card->save();
        DealLog::add_log($user->id, 0, $order->money, 2, '购买礼品卡(微信)');
    }
    public function buy_bag($wallet, $user, $order)
    {
        $user->robe_num = 3;
        $user->save();
        DealLog::add_log($user->id, 0, $order->money, 2, '升级衣袋(微信)');
    }
}
